import router from './router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import NProgress from '@/utils/nprogress'

const whiteList = ['/login', '/register'] // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userStore = useUserStore()

  if (userStore.token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (userStore.role) {
        next()
      } else {
        try {
          await userStore.getInfo()
          next({ ...to, replace: true })
        } catch (error) {
          await userStore.logout()
          ElMessage.error(error.message || '获取用户信息失败')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
}) 